<template>
  <div class="data-list">
    <!-- 列表模式 -->
    <template v-if="!showForm">
      <div class="list-header">
        <div class="header-left">
          <h2>{{ model }} 列表</h2>
        </div>
        <div class="header-right">
          <el-button type="primary" @click="handleCreate" :icon="Plus">
            新建
          </el-button>
          <el-button @click="refreshData" :icon="Refresh">
            刷新
          </el-button>
        </div>
      </div>

      <el-table
        v-loading="loading"
        :data="records"
        border
        stripe
        style="width: 100%"
      >
        <!-- 确保字段存在时才渲染列 -->
        <template v-if="fields.length > 0">
          <el-table-column
            v-for="field in fields"
            :key="field.name"
            :prop="field.name"
            :label="field.label"
            :min-width="field.width"
            show-overflow-tooltip
          >
            <template #default="{ row }">
              {{ formatFieldValue(row, field) }}
            </template>
          </el-table-column>
        </template>

        <el-table-column 
          label="操作" 
          width="200" 
          fixed="right"
          align="center"
        >
          <template #default="{ row }">
            <el-button-group v-if="row">
              <el-button 
                type="primary" 
                size="small" 
                @click="handleView(row)"
                :icon="Document"
              >
                查看
              </el-button>
              <el-button 
                type="warning" 
                size="small" 
                @click="handleEdit(row)"
                :icon="Edit"
              >
                编辑
              </el-button>
              <el-button 
                type="danger" 
                size="small" 
                @click="handleDelete(row)"
                :icon="Delete"
              >
                删除
              </el-button>
            </el-button-group>
          </template>
        </el-table-column>
      </el-table>

    </template>

    <!-- 表单模式 -->
    <template v-else>
      <div class="form-header">
       
        <el-button @click="handleBack" :icon="Back">
          返回列表
        </el-button>
      </div>
      <data-form
        :key="`${formMode}-${currentRecord.id || 'new'}`"
        :mode="formMode"
        :fields="fields"
        :record="currentRecord"
        @submit="handleSubmit"
        @cancel="handleBack"
      />
    </template>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, watch } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import axios from 'axios'
import DataForm from './DataForm.vue'
import { 
  Plus, Refresh, Document, Edit, Delete, Back 
} from '@element-plus/icons-vue'

const route = useRoute()
const router = useRouter()
const model = ref(route.params.model || 'device')
const modelInfo = ref(null)
const fields = ref([])
const records = ref([])
const loading = ref(false)
const showForm = ref(false)
const formMode = ref('create')
const currentRecord = ref({})
const currentPage = ref(1)
const pageSize = ref(10)
const totalRecords = ref(0)
const showDetail = ref(false)

const loadModelInfo = async () => {
  try {
    const { data } = await axios.get(`/api/models/${model.value}`)
    modelInfo.value = data
    console.log('Model Info:', modelInfo.value)
    
    // 从模型定义中获取字段信息
    if (data.fields) {
      let modelFields = []
      try {
        if (typeof data.fields === 'string') {
          modelFields = JSON.parse(data.fields)
        } else if (Array.isArray(data.fields)) {
          modelFields = data.fields
        }
        
        fields.value = modelFields.map(field => ({
          name: field.name,
          label: field.displayName || field.name,
          type: field.type,
          required: field.required,
          width: (field.displayName || field.name).length * 15 + 80
        }))
      } catch (err) {
        console.error('解析字段定义失败:', err)
      }
    }
  } catch (error) {
    console.error('加载模型信息失败:', error)
    ElMessage.error('加载模型信息失败')
  }
}

const loadRecords = async () => {
  if (!model.value) return
  
  loading.value = true
  try {
    const { data } = await axios.get(`/api/data/${model.value}`, {
      params: {
        page: currentPage.value,
        size: pageSize.value
      }
    })
    console.log('获取到的原始数据:', data)
    
    if (data?.records) {
      records.value = data.records
      totalRecords.value = data.total || 0
      
      // 如果字段还未定义，从第一条记录中获取
      if (fields.value.length === 0 && records.value.length > 0) {
        const firstRecord = records.value[0]
        fields.value = Object.entries(firstRecord)
          .filter(([key]) => key !== 'id') // 排除 id 字段
          .map(([key, value]) => ({
            name: key,
            label: key.charAt(0).toUpperCase() + key.slice(1), // 首字母大写
            type: typeof value,
            width: key.length * 15 + 80 // 根据字段名长度动态设置宽度
          }))
        console.log('生成的字段定义:', fields.value)
      }
    }
    
    console.log('处理后的记录:', records.value)
    console.log('当前字段定义:', fields.value)
  } catch (error) {
    console.error('加载数据失败:', error)
    ElMessage.error('加载数据失败')
    records.value = []
  } finally {
    loading.value = false
  }
}

// 格式化字段值
const formatFieldValue = (row, field) => {
  const value = row[field.name]
  if (value === null || value === undefined) return '-'
  return String(value)
}

// 监听路由变化
watch(() => route.params.model, async (newModel) => {
  if (newModel && newModel !== model.value) {
    model.value = newModel
    await refreshData()
  }
}, { immediate: true })

// 组件挂载时加载数据
onMounted(() => {
  loadModelInfo()
  loadRecords()
})

// 返回列表
const handleBack = () => {
  // 确认是否放弃更改
 
      resetForm()
   
}

// 处理查看
const handleView = (row) => {
  console.log('查看数据:', row)
  formMode.value = 'view'
  currentRecord.value = JSON.parse(JSON.stringify(row))
  showForm.value = true
}

// 处理创建
const handleCreate = () => {
  formMode.value = 'create'
  currentRecord.value = {}
  showForm.value = true
}

// 处理编辑
const handleEdit = async (row) => {
  try {
    // 确保已加载模型信息和字段定义
    if (!modelInfo.value || fields.value.length === 0) {
      await loadModelInfo()
    }
    
    formMode.value = 'edit'
    // 深拷贝记录数据
    currentRecord.value = JSON.parse(JSON.stringify(row))
    showForm.value = true
    
    console.log('编辑模式:', {
      formMode: formMode.value,
      currentRecord: currentRecord.value,
      fields: fields.value
    })
  } catch (error) {
    console.error('准备编辑失败:', error)
    ElMessage.error('准备编辑失败')
  }
}

// 处理删除
const handleDelete = async (row) => {
  try {
    await ElMessageBox.confirm('确定要删除这条记录吗？', '提示', {
      type: 'warning'
    })
    console.log('删除记录:', fields.value)
    await axios.delete(`/api/data/${model.value}/${row.id}`)
    ElMessage.success('删除成功')
    await loadRecords()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除失败:', error)
      ElMessage.error('删除失败')
    }
  }
}

// 处理表单提交
const handleSubmit = async () => {
  try {
     // 重置表单状态
    showForm.value = false
    formMode.value = 'create'
    currentRecord.value = {}
    
    // 刷新数据列表
    await refreshData()
  } catch (error) {
    console.error('提交失败:', error)
    ElMessage.error(error.response?.data?.error || error.message || '提交失败')
  } finally {
    loading.value = false
  }
}

// 刷新数据
const refreshData = async () => {
  try {
    loading.value = true
    await loadModelInfo() // 重新加载模型信息
    await loadRecords()   // 重新加载记录
    ElMessage.success('数据已刷新')
  } catch (error) {
    console.error('刷新数据失败:', error)
    ElMessage.error('刷新数据失败')
  } finally {
    loading.value = false
  }
}

// 计算标题
const formTitle = computed(() => {
  const action = {
    create: '新建',
    edit: '编辑',
    view: '查看'
  }[formMode.value]
  
  return `${action}${modelInfo.value?.displayName || '数据'}`
})

// 添加重置表单的函数
const resetForm = () => {
  showForm.value = false
  currentRecord.value = {}
  formMode.value = 'create'
}
</script>

<style scoped>
.data-list {
  padding: 20px;
  height: 100%;
  display: flex;
  flex-direction: column;
}

.list-header,
.form-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.header-left h2 {
  margin: 0;
  font-size: 18px;
}

.header-right .el-button {
  margin-left: 10px;
}

.el-table {
  flex: 1;
}

.el-button-group .el-button {
  margin-right: 0;
}

:deep(.el-table__body-wrapper) {
  overflow-y: auto;
}

:deep(.el-table__cell) {
  word-break: break-all;
}

.debug-info {
  margin-top: 20px;
  padding: 10px;
  background-color: #f5f5f5;
  border-radius: 4px;
  font-family: monospace;
}
</style> 
